﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Site.ViewModels;
using SDT.Lib.Common;
using SDT.Site.Properties;
using SDT.Model;
using System.Linq.Dynamic;
using System.IO;
namespace SDT.Site.Controllers
{
    public class CompanyController : Controller
    {
        //
        // GET: /Company/
        SDTDataContext eDataContext = new SDTDataContext();
        #region article
        public ActionResult Index()
        {
            try
            {
                CompanyIndexModels p = new CompanyIndexModels();
                p.CompanyTypies = eDataContext.CompanyTypes.OrderBy(string.Format("{0} {1}", "ID", "asc")).ToList();
                p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.CompanyRootUrl;
                p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.CompanyRootPath;
                return View(p);
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View();
            }
        }
        // Vietlv: add parameter "int? companyID" for program (int? companyID)
        public ActionResult List(int id)
        {
            try
            {
                var idcg = Request["id"];
                var companyID = Request["companyID"] != null ? Convert.ToInt32(Request["companyID"]) : 0;
                ArticleIndexViewModel a = new ArticleIndexViewModel();
                var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("company.PageNumber", "page", 1));
                var pageIndex = pageNumber - 1;
                // Vietlv add condition companyID > 0
                if (companyID > 0)
                { 
                    a.Articles = ArticleManager.GetArticlesByCompany(id, companyID, string.Empty, 0, 1, "ID", "desc", pageIndex, Utils.ParseInt(Settings.Default.PageSize)); 
                }
                else
                {
                    a.Articles = ArticleManager.GetArticles(id, string.Empty, 0, 1, "ID", "desc", pageIndex, Utils.ParseInt(Settings.Default.PageSize));
                }

                a.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
                a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
                a.Category = eDataContext.ArticleCategories.Where(e => e.ID == id).SingleOrDefault();
                return View(a);
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View();
            }
        }
        /// <summary>
        /// id: Company ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Listing(int id)
        {
            try
            {
                var catid = ConfigManager.GetTindoanhnghiep();
                var company = eDataContext.Companies.Where(e => e.ID == id).SingleOrDefault();
                ArticleIndexViewModel a = new ArticleIndexViewModel();
                var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("company.PageNumber", "page", 1));
                var pageIndex = pageNumber - 1;
                a.Articles = ArticleManager.GetArticles(catid,null,id, string.Empty, 0, 1, "ID", "desc", pageIndex, Utils.ParseInt(Settings.Default.PageSize));
                a.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
                a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
                a.Category = eDataContext.ArticleCategories.Where(e => e.ID == catid).SingleOrDefault();
                return View(a);
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View();
            }
        }
        
        public ActionResult Details(int id)
        {
            ArticleDetailViewModel a = new ArticleDetailViewModel();
            a.Article = eDataContext.Articles.Where(e => e.ID == id).SingleOrDefault();
            a.Article.nViews += 1;
            eDataContext.SubmitChanges();
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult Focus(int number, int skip, int catid, string title, string order, string orderDir)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 1, 1, order, orderDir, number, skip);
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            a.Category = catid > 0 ? eDataContext.ArticleCategories.Where(e => e.ID == catid).FirstOrDefault() : null;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult GetTop(int number, int typeid, string title, string order, string orderDir)
        {
            var p = new CompanyListModels();
            var l = CompanyManager.GetList(number, typeid, 0, 0, 0, 1, order, orderDir);
            ViewData["Title"] = title;
            p.Companies = l;
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.CompanyRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.CompanyRootPath;
            return View(p);
        }
        [ChildActionOnly]
        public ActionResult GetByCat(int number, int typeid, string title, string order, string orderDir)
        {
            var p = new CompanyListModels();
            var l = CompanyManager.GetList(number, typeid, 0, 0, 0, 1, order, orderDir);
            ViewData["Title"] = title;
            p.Companies = l;
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.CompanyRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.CompanyRootPath;
            p.CompanyType = eDataContext.CompanyTypes.Where(e => e.ID == typeid).SingleOrDefault();
            return View(p);
        }
        /// <summary>
        /// Function Name: OtherItems
        /// Description: Get other items in article have catid = catid of current article
        /// </summary>
        /// <param name="id"></param>
        /// <param name="number"></param>
        /// <param name="title"></param>
        /// <param name="greaterYN"></param>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult OtherItems(int id, int number, string title, bool greaterYN)
        {
            var a = new ArticleListViewModel();
            var current_article = eDataContext.Articles.Where(e => e.ID == id).SingleOrDefault();
            var l = eDataContext.Articles.Where(e => e.ArticleCategory.ID == current_article.CatID)
                .Where(e => e.PubYN == true)
                .Where(e => e.ID != id)
                .Where(e => greaterYN == false ? e.AddDate <= current_article.AddDate : e.AddDate >= current_article.AddDate).OrderByDescending(e => e.ID).Take(number).ToList(); ;
            ViewData["Title"] = title;
            a.Articles = l;
            return View(a);
        }
        [ChildActionOnly]
        public ActionResult NewestByCat(int number, int skip, int catid, string title, string order, string orderDir)
        {
            var a = new ArticleListViewModel();
            var l = ArticleManager.GetList(catid, string.Empty, 0, 1, order, orderDir, number, skip);
            ViewData["Title"] = title;
            a.Articles = l;
            a.RootImageUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            a.ImagePath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
            return View(a);
        }
        #endregion


        #region List company
        public ActionResult Directories(int? id, int? cityid, int? distrid, int? page)
        {
            if (page == null) page = 1; ;
            var pageIndex = page.Value - 1;
            var pageSize = Convert.ToInt32(UserState.getUserStateFromRequest("company.PageSize", "pageSize", Settings.Default.ProductPageSize));
            string order = UserState.getUserStateFromRequest("company.order", "order", "ID").ToString();
            string orderDir = UserState.getUserStateFromRequest("company.orderDir", "orderDir", "desc").ToString();

            CompanyIndexModels p = new CompanyIndexModels();
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.CompanyRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.CompanyRootPath;

            p.CompanyType = id.HasValue && id.Value > 0 ? eDataContext.CompanyTypes.Where(e => e.ID == id).SingleOrDefault() : null;
            p.City = cityid.HasValue && cityid.Value > 0 ? eDataContext.Cities.Where(e => e.ID == cityid).SingleOrDefault() : null;
            p.District = distrid.HasValue && distrid.Value > 0 ? eDataContext.Districts.Where(e => e.ID == distrid).SingleOrDefault() : null;

            p.CityID = cityid.HasValue ? cityid.Value : 0;
            p.DistrictID = distrid.HasValue ? distrid.Value : 0;
            p.CompanyTypeID = id.HasValue ? id.Value : 0; ;
            p.Keyword = Request["key"] != null ? Request["key"] : string.Empty;

            p.Companies = CompanyManager.GetList(id, cityid, distrid, p.Keyword, 0, 1, order, orderDir, pageIndex, pageSize);
            return View(p);
        }
        public ActionResult More(int id)
        {
            CompanyDetailModels p = new CompanyDetailModels();
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.CompanyRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.CompanyRootPath;
            p.Company = id > 0 ? eDataContext.Companies.Where(e => e.ID == id).SingleOrDefault() : null;
            return View(p);
        }
        [HttpPost]
        public ActionResult Search()
        {
            CompanyListModels p = new CompanyListModels();
            var catID = Utils.ParseInt(Request["ddlType"], 0);
            var cityID = Utils.ParseInt(Request["ddlCity"], 0);
            var districtID = Utils.ParseInt(Request["ddlDistrict"], 0);
            var keyword = Request["txtKeyword"] != null ? Request["txtKeyword"] : string.Empty;
            string path = string.Format("directories/{0}/{1}/{2}", catID, cityID, districtID);

            if (p.Keyword != null && p.Keyword != string.Empty) path = path + "?key=" + p.Keyword;
            return RedirectToAction(path, "company");
        }
        [ChildActionOnly]
        public ActionResult Search(int id, int cityid, int distrid)
        {
            CompanyListModels p = new CompanyListModels();
            p.CompanyTypies = eDataContext.CompanyTypes.OrderBy(string.Format("{0} {1}", "ID", "asc")).ToList();
            p.Cities = eDataContext.Cities.OrderBy(string.Format("{0} {1}", "Name", "asc")).ToList();
            p.Districts = cityid > 0 ? eDataContext.Districts.Where(e => e.CityID == cityid).ToList() : new List<District>();
            p.CompanyTypeID = id;
            p.CityID = cityid;
            p.DistrictID = distrid;
            p.Keyword = Request["key"] != null ? Request["key"] : string.Empty;
            return View(p);
        }
        
        [ChildActionOnly]
        public ActionResult GetLeft(int id)
        {
            CompanyListModels p = new CompanyListModels();
            p.CompanyTypies = eDataContext.CompanyTypes.OrderBy(string.Format("{0} {1}", "ID", "asc")).ToList();
            p.CompanyTypeID = id;
            // added by Vietlv: 
            // Get Array id CompanyType of current company
            var listCompanyTypeID = eDataContext.CompanyTypeMaps.Where(e => e.CompanyID == id).Select(e => e.CompanyTypeID).ToList();
            p.TypeOfCurrentCom = listCompanyTypeID;
            return View(p);
        }
        [ChildActionOnly]
        public ActionResult GetCities(int id, int cityid)
        {
            CompanyListModels p = new CompanyListModels();
            p.CompanyTypeID = id;
            p.CityID = cityid;
            var c = eDataContext.Cities.
                Where(e =>id>0? e.Companies.
                    Where(k => k.CompanyTypeMaps.
                        Where(m => m.CompanyTypeID == id).ToList().Count > 0).ToList().Count > 0:true).AsQueryable();
            p.Cities = c.OrderByDescending(e => e.Companies.ToList().Count).ToList();
            return View(p);
        }
        [ChildActionOnly]
        public ActionResult Hot(int number, int typeid, int cityid, int distrid,string title, string order, string orderDir)
        {
            CompanyListModels p = new CompanyListModels();
            p.Companies = CompanyManager.GetList(number, typeid, cityid, distrid,1, 1, order, orderDir);
            p.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.CompanyRootUrl;
            p.ImagePath = Settings.Default.SiteRootPath + Settings.Default.CompanyRootPath;
            ViewData["Title"] = title;
            return View(p);
        }

        [Authorize]
        public ActionResult Introduce()
        {
            CompanyEditViewModel c = new CompanyEditViewModel();
            c.Company = eDataContext.Companies.Where(e => e.AddBy == UserManager.GetUserId()).FirstOrDefault();
            if (c.Company == null) c.Company = new Company();
            c.Cities = eDataContext.Cities.OrderBy(string.Format("{0} {1}", "Name", "asc")).ToList();
            c.CompanyTypes = eDataContext.CompanyTypes.ToList();
            c.ImageUrl = Settings.Default.SiteRootUrl + Settings.Default.CompanyRootUrl;
            c.ImagePath = Settings.Default.SiteRootPath + Settings.Default.CompanyRootPath;
            c.Districts = c.Company.ID == 0 ? new List<District>() : c.Company.City.Districts.ToList();            
            return View(c);
        }


        [HttpPost]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult Introduce(CompanyEditViewModel c)
        {
            try
            {
                if (Request["CaptchaText"] == HttpContext.Session["captchastring"].ToString())
                {
                    if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                    eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                    // TODO: Add insert logic here
                    c.Company = eDataContext.Companies.Where(e => e.AddBy == UserManager.GetUserId()).SingleOrDefault();
                    var isUpdated = false;
                    if (c.Company == null)
                    {
                        c.Company = new Company();
                    }
                    else
                    {
                        isUpdated = true;
                    }
                    UpdateModel(c);
                    var pid = Request["ddlCity"] != "" ? Utils.ParseInt(Request["ddlCity"]) : 0;
                    var did = Request["ddlDistrict"] != "" ? Utils.ParseInt(Request["ddlDistrict"]) : 0;
                    if (pid > 0) c.Company.CityID = pid;
                    c.Company.DistrictID = did;
                    c.Company.AddBy = UserManager.GetUserId();
                    c.Company.AddDate = DateTime.Now;
                    c.Company.ActiveYN = false;
                    c.Company.HotYN = false;
                    c.Company.Priority = 0;
                    if (isUpdated == false)
                    {
                        eDataContext.Companies.InsertOnSubmit(c.Company);
                    }
                    eDataContext.SubmitChanges();
                    // Insert CompanyTypeMap
                    var listCompanyType = eDataContext.CompanyTypes.ToList();
                    var list = eDataContext.CompanyTypeMaps.Where(e => e.CompanyID == c.Company.ID).ToList();
                    eDataContext.CompanyTypeMaps.DeleteAllOnSubmit(list);
                    foreach (var item in listCompanyType)
                    {
                        var isSelected = Request["CompanyType." + item.ID] != null && Request["CompanyType." + item.ID].ToString().Equals("false") == false ? true : false;
                        if (isSelected == true)
                        {
                            var companyTypeMap = new CompanyTypeMap();
                            companyTypeMap.CompanyID = c.Company.ID;
                            companyTypeMap.CompanyTypeID = item.ID;
                            eDataContext.CompanyTypeMaps.InsertOnSubmit(companyTypeMap);
                            eDataContext.SubmitChanges();
                        }
                    }
                    // Upload file image
                    HttpPostedFileBase fileName = Request.Files["CompanyFile"];
                    if (fileName != null && fileName.ContentLength > 0)
                    {
                        c.Company.ImagePath = Path.GetFileName(fileName.FileName);
                        Uploads.UploadFile(fileName, string.Format("{0}\\{1}", Settings.Default.SiteRootPath, Settings.Default.CompanyRootPath), "" + c.Company.ID);
                    }
                    eDataContext.SubmitChanges();
                    eDataContext.Transaction.Commit();

                    return View("Success");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.ERR_CAPTCHA_VALIDATE;
                    return View(c);
                }
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View("Fail");
            }
        }

        [Authorize]
        public ActionResult Create()
        {
            ArticleInputModels a = new ArticleInputModels();
            a.Category = eDataContext.ArticleCategories.Where(e => e.ID ==Utils.ParseInt(Settings.Default.ArticleTindoanhnghiep)).SingleOrDefault();
            return View(a);
        }


        /// <summary>
        /// Author: Takamaru Nguyen
        /// Date: 04/08/2011
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult Create(ArticleInputModels m)
        {
            try
            {
                if (Request["CaptchaText"] == HttpContext.Session["captchastring"].ToString())
                {
                    m.Category = eDataContext.ArticleCategories.Where(e => e.ID == Utils.ParseInt(Settings.Default.ArticleTindoanhnghiep)).SingleOrDefault();
                    UpdateModel(m.Article);
                    m.Article.CatID = m.Category.ID;
                    m.Article.Priority = 0;
                    m.Article.AddDate = DateTime.Now;
                    m.Article.PubYN = false;
                    m.Article.Summary = m.Article.Title;
                    m.Article.nViews = 0;
                    m.Article.AddBy = UserManager.GetUserId();
                    var c = eDataContext.Companies.Where(e => e.AddBy == UserManager.GetUserId()).FirstOrDefault();
                    if (c != null)
                    {
                        eDataContext.Articles.InsertOnSubmit(m.Article);
                        eDataContext.SubmitChanges();
                        //Image upload
                        HttpPostedFileBase fileImage = Request.Files["ImagePath"];
                        if (fileImage != null && fileImage.ContentLength > 0)
                        {
                            m.Article.ImagePath = Path.GetFileName(fileImage.FileName);
                            eDataContext.SubmitChanges();
                            Uploads.UploadFile(fileImage, string.Format("{0}\\{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath), "" + m.Article.ID);
                        }
                        ArticleCompanyMap map = new ArticleCompanyMap();
                        map.ArticleID = m.Article.ID;
                        map.CompanyID = c.ID;
                        eDataContext.ArticleCompanyMaps.InsertOnSubmit(map);
                        eDataContext.SubmitChanges();
                    }
                    else {
                        ViewData[Messages.MessageInfo] = Messages.ERR_SEND_ARTICLE_COMPANY;
                        return View(m); 
                    }
                    //Check user company
                    
                    return View("Success");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.ERR_CAPTCHA_VALIDATE;
                    return View(m);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteLog(ex);
                return View("Fail");
            }
        }
        #endregion
    }
}
